﻿Imports System.Xml
Imports System.Text

''' <summary>
''' 处理DataTable与XML的写入
''' </summary>
''' <remarks></remarks>
Public Class XmlWriteHelper

    ''' <summary>
    ''' 本类中需要使用的常量
    ''' </summary>
    ''' <remarks></remarks>
    Private Structure ConstantWord

        Const CONSTANT_DATA = "DATA"
        Const CONSTANT_DATA_INPUT_DBF = "INPUT-DBF"
        Const CONSTANT_DATA_OUTPUT_XML = "OUTPUT-XML"
        Const CONSTANT_DATA_ROW_COUNT = "COUNT"
        Const CONSTANT_DATA_ROW = "DATA_ROW"

    End Structure

    ''' <summary>
    ''' 将dtResource的内容写入到XML中
    ''' </summary>
    ''' <param name="inputPath"></param>
    ''' <param name="outputPath"></param>
    ''' <param name="dtResource"></param>
    ''' <param name="columns"></param>
    ''' <remarks></remarks>
    Public Shared Sub WriteDataTableToXml(inputPath As String, outputPath As String, dtResource As DataTable, columns As String())

        Dim writer As XmlTextWriter = New XmlTextWriter(outputPath, Encoding.GetEncoding("utf-8"))
        writer.WriteStartDocument()

        '如果需要绑定一个样式信息文件，则添加此行，也可在打印出的XML文件中手动添加
        '<?xml-stylesheet type='text/xsl' href='<CHOOSE A XSLT>.xslt'?> 
        'writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='<CHOOSE A XSLT OR DELETE THIS LINE!>.xslt'")

        writer.WriteStartElement(ConstantWord.CONSTANT_DATA)

        '打印数据表行数，源DBF文件地址，打印落地XML文件地址
        writer.WriteAttributeString(ConstantWord.CONSTANT_DATA_ROW_COUNT, dtResource.Rows.Count)
        writer.WriteAttributeString(ConstantWord.CONSTANT_DATA_INPUT_DBF, inputPath)
        writer.WriteAttributeString(ConstantWord.CONSTANT_DATA_OUTPUT_XML, outputPath)

        '逐行打印
        For Each drRow As DataRow In dtResource.Rows

            writer.WriteStartElement(ConstantWord.CONSTANT_DATA_ROW)

            For Each strColumnName As String In columns
                writer.WriteElementString(strColumnName, drRow(strColumnName).ToString)
            Next

            writer.WriteEndElement()

        Next

        writer.WriteEndElement()
        writer.WriteEndDocument()
        writer.Close()

    End Sub

End Class
